package com.shangxian.giveithome.service.impl;


import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.code.FeiCode;
import com.shangxian.giveithome.code.UserCode;
import com.shangxian.giveithome.controller.MechanismServer;
import com.shangxian.giveithome.controller.PetFeiServer;
import com.shangxian.giveithome.entity.*;
import com.shangxian.giveithome.entity.community.NoticeCenter;
import com.shangxian.giveithome.entity.community.UserList;
import com.shangxian.giveithome.entity.move.*;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.CommentMapper;
import com.shangxian.giveithome.mapper.UserDataMapper;
import com.shangxian.giveithome.mapper.UserMapper;
import com.shangxian.giveithome.properties.UserProperties;
import com.shangxian.giveithome.service.FeiUserService;
import com.shangxian.giveithome.service.UserService;
import com.shangxian.giveithome.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.shangxian.giveithome.utils.DateTime.YMD;
import static com.shangxian.giveithome.utils.DateTime.getTime;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserDataMapper userDataMapper;


    @Resource
    private PetFeiServer petFeiServer;

    @Autowired
    private FeiUserService feiUserService;

    @Resource
    private MechanismServer mechanismServer;

    @Autowired
    private IGenerator iGenerator;


    @Autowired
    private RedisUtils redisUtils;

    /**
     * 注册用户
     *
     * @param userInfo
     * @return
     */
    @Transactional
    @Override
    public UserDetails create(UserInfo userInfo) {
        Integer count = userMapper.queryByOpenId(userInfo.getOpenId());
        //判断用户是否已存在
        if (count > 0) {
            ExceptionUtils.error(UserCode.USER_EXISTENCE);
        }
        User user = new User();
        //把userinfo中的属性值拷贝到user中
        BeanUtils.copyProperties(userInfo, user);
        user.setUuid(getUUID());
        user.setRole(UserProperties.ROLE_USER);
        user.setVolunteerTime(getTime(YMD));
        /**
         * cf
         * 吴上面注释，林下面
         */
        //user.setVolunteerTime(0D);
        userMapper.save(user);
        userMapper.createData(user.getId());
        return iGenerator.convert(user, UserDetails.class);
    }

    /**
     * cf
     * 林获取UULD方法
     * @return
     */
    private String getUUID() {
        String uuid = UUIDUtils.generateShortUuid();
        Integer count = userMapper.queryByUuid(uuid);
        //判断用户是否已存在
        if (count > 0) {
            return getUUID();
        }
        return uuid;
    }

    /**
     * 完善用户信息
     *
     * @param userPerfect
     * @param request
     */
    @Transactional
    @Override
    public void perfact(UserPerfect userPerfect, HttpServletRequest request) {
        UserDetails userDetails = redisUtils.getHeader(request);
        userPerfect.setId(userDetails.getId());
        int i = userMapper.perface(userPerfect);
        if (i == 0) {
            ExceptionUtils.error(UserCode.USER_UPDATE_ERROR);
        }
        //使用BeanUtils.copyProperties方法进行对象之间属性的赋值
        // ，避免通过get、set方法一个一个属性的赋值
//
//     * 将源对象的属性拷贝到目标对象
//     * @param source 源对象 第一个参数
//     * @param target 目标对象  第二个参数
        BeanUtils.copyProperties(userPerfect, userDetails);
        redisUtils.upUserDetails(request, userDetails);
    }

    /**
     * 更新用户信息
     *
     * @param putUser
     * @param request
     */
    @Override
    @Transactional
    public UserDetails updateUser(PutUser putUser, HttpServletRequest request) {
        UserDetails userDetails = redisUtils.getHeader(request);
        PutUserFei putUserFei = new PutUserFei();
        BeanUtils.copyProperties(putUser, putUserFei);
        putUserFei.setOpenId(userDetails.getOpenId());
        int i = userMapper.updateUser(putUserFei);
        if (i == 0) {
            ExceptionUtils.error(UserCode.USER_UPDATE_ERROR);
        }
        UserDetails userDetails1 = feiUserService.queryByOpenId(userDetails.getOpenId());
        redisUtils.upUserDetails(request, userDetails1);
        userDetails1.setOpenId(null);
        return userDetails1;
    }

    /**
     * 查询已领养信息
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails queryByAdoption(Long id, Pageable pageable) {
        PageableDetails pageableDetails = petFeiServer.queryByAdoptionUs(id, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 查看已送养-待领养
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails queryByPlace(Long id, Pageable pageable) {
        PageableDetails pageableDetails = petFeiServer.queryByPlaceUs(id, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 查看已送养-历史
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails queryByPlaceHistory(Long id, Pageable pageable) {
        PageableDetails pageableDetails = petFeiServer.queryByPlaceHistory(id, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 查询寻主-寻找中
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails searchPeople(Long id, Pageable pageable) {
        PageableDetails pageableDetails = petFeiServer.searchPeople(id, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 查看寻主-已找到
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails searchPeopleHistory(Long id, Pageable pageable) {
        PageableDetails pageableDetails = petFeiServer.searchPeopleHistory(id, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 查看用户数据
     *
     * @param id
     * @return
     */
    @Override
    public UserData queryUserData(Long id) {
        UserData userData = userDataMapper.findById(id);
        if (userData == null) {
            ExceptionUtils.error(FeiCode.FEI_ERROR);
        }
        return userData;
    }

    /**
     * 查看寻宠-寻找中
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails searchPet(Long id, Pageable pageable) {
        PageableDetails pageableDetails = petFeiServer.searchPet(id, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 查看寻宠-历史
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails searchPetHistory(Long id, Pageable pageable) {
        PageableDetails pageableDetails = petFeiServer.searchPetHistory(id, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 根据用户id查询活动数据
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails queryMyActivity(Long id, Long offSet, Pageable pageable) {
        PageableDetails pageableDetails = mechanismServer.queryUserActivity(id, offSet, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 根据用户id查询活动数据-历史
     *
     * @param id
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails queryMyActivityHistory(Long id, Long offSet, Pageable pageable) {
        PageableDetails pageableDetails = mechanismServer.queryUserActivityHistory(id, offSet, pageable);
        if (pageableDetails == null) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        return pageableDetails;
    }

    /**
     * 根据id集合查询用户集合
     *
     * @param ids
     * @return
     */
    @Override
    public List<UserSimple> queryByIds(List<Long> ids) {
        List<User> user = userMapper.queryById(ids);
        return iGenerator.convert(user, UserSimple.class);
    }

    /**
     * 根据id查询用户简单信息
     *
     * @param id
     * @return
     */
    @Override
    public UserSimple queryById(Long id) {
        return userMapper.queryByUserSimple(id);
    }

    @Override
    public List<User> queryRole3() {
        return userMapper.queryRole3();
    }

    @Override
    public int moveuser() {
        List<User_copy1> user_copy1List = userMapper.selectuser_copy1();
        for (User_copy1 u : user_copy1List) {
            User user = new User();
            user.setOpenId(u.getUserId());
            user.setName(u.getUserNickName());
            user.setPhone(u.getUserPhone());
            user.setPicture("1");
            userMapper.istuer(user);
        }
        return 0;
    }

    @Override
    public int movepet() {
        //原pet表迁移，迁移至img pet place，已测试成功，暂却img中的字段不明确
        List<Pet_copy1> pet_copy1s = userMapper.setlectpet_copy1();
        for (Pet_copy1 p : pet_copy1s) {
            Pet pet = new Pet();
            pet.setUsId(userMapper.selectopid(p.getPublisherId()));
            pet.setName(p.getPetName());
            pet.setAge(p.getPetAge());
            pet.setCreateTime(p.getPetPushDate());
            pet.setSubordinate(4);
            pet.setDescribe(p.getPetAboutMe());
            pet.setSterilization(p.getPetSterilization());
            pet.setVaccine(p.getPetVaccine());
            pet.setSex(p.getPetSex());
            pet.setType(p.getPetCategory());

            Long varieties;
//人工填入类别
//            Varieties v=new Varieties();
//            v.setName(p.getPetVarieties());
//            varieties=userMapper.selectvaesid(v);
//
//            pet.setVarieties(String.valueOf(varieties));
            userMapper.istpet(pet);
            //领养数据导入
            Place place = new Place();
            place.setPetId(userMapper.selectid1(pet));
            long b = userMapper.selectopid(p.getPublisherId());
            place.setUsId(b);
            place.setWechat(p.getContactsWechat());
            place.setCreateTime(p.getPetPushDate());
            place.setPhone(p.getContactsPhone());
            place.setImgId(Long.valueOf(p.getFileName()));
            userMapper.istpla(place);
            List<Img_copy1> img_copy1s = userMapper.selectSimg(p.getPublisherId());
            for (Img_copy1 img_copy1 : img_copy1s) {
                Img i = new Img();
                i.setPath(img_copy1.getPath());
                i.setKeyId(Long.valueOf(img_copy1.getFileName()));
                i.setUsId(userMapper.selectopid(p.getPublisherId()));
                userMapper.istimg(i);
            }

//导入img
//            List<Img_copy1> img_copy1s = userMapper.selectimg(p.getPublisherId());
//            for (Img_copy1 img_copy1 : img_copy1s) {
//                Img i = new Img();
//                i.setKeyId(Long.valueOf(p.getFileName()));
//                i.setUsId(b);
//                i.setPath(img_copy1.getPath());
//                userMapper.istimg(i);
//            }
//            //youcuo
//            place.setImgId(Long.valueOf(p.getFileName()));

        }
        return 0;
    }

    // 根据id清空该用户在redis中的数据
    @Override
    public void removeUserDetails(Long id) {
        redisUtils.deleteByPrefix(Base64Utils.encodeToString(id.toString()));
    }

    @Override
    public PageableDetails noticeCenter(HttpServletRequest request, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        UserDetails userDetails = redisUtils.getHeader(request);
        int total = commentMapper.findCommentCountByUsId(userDetails.getId());
        if (total ==0) {
            return new PageableDetails<>(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
            List<NoticeCenter> noticeMessages = userMapper.findNoticeMessage(userDetails.getId(), pageNumber * pageSize, pageSize);
            List<Long> CuIds = noticeMessages.stream().map(NoticeCenter::getCuId).collect(Collectors.toList());
            System.out.println(CuIds);
            List<UserList> userLists = userMapper.findAllUserMessageById(CuIds);
            noticeMessages.forEach(NoticeCenter -> {
                System.out.println(NoticeCenter.toString());
                NoticeCenter.setName("");
                NoticeCenter.setPath("");
                for (UserList user : userLists) {
                    if (user.getId().equals(NoticeCenter.getCuId())) {
                        NoticeCenter.setName(user.getName());
                        NoticeCenter.setPath(user.getPicture());
                        break;
                    }
                }
            });
        return new PageableDetails<>(pageNumber,pageSize,total,returnPages(total,pageSize),noticeMessages);
    }

    @Override
    public int movespeop() {
        List<Sreach_people> sreach_peopleList = userMapper.selectschp();
        //todo 导入寻主  导入宠物
        for (Sreach_people s : sreach_peopleList) {
            Pet pet = new Pet();
            pet.setUsId(userMapper.selectopid(s.getAppleId()));
            pet.setName("0");
            pet.setAge("0");
            pet.setCreateTime(s.getPublishTime());
            pet.setSubordinate(2);
            pet.setDescribe(s.getPetMessage());
            pet.setSterilization("未知");
            pet.setVaccine("未知");
            pet.setSex(s.getPetSex());
            pet.setType(s.getPetCategory());
            Long varieties;
            Varieties v = new Varieties();
            v.setName(s.getPetVarieties());
            varieties = userMapper.selectvaesid(v);
            pet.setVarieties(String.valueOf(varieties));
            userMapper.istpet(pet);
            //todo 导入寻主
            SearchPeople searchPeople = new SearchPeople();
            searchPeople.setUsId(userMapper.selectopid(s.getAppleId()));
            searchPeople.setPetId(userMapper.selectid2(pet));
            searchPeople.setWechat(s.getPublisherWechat());
            searchPeople.setCreateTime(s.getPublishTime());
            searchPeople.setCity(s.getFindCityArea());
            searchPeople.setCounty(s.getFindCountyArea());
            searchPeople.setProvince("");
            searchPeople.setAddress(s.getFindDetailedArea());
            searchPeople.setPhone(s.getPublisherPhone());
            if(s.getSearchMasterState()){searchPeople.setStatus(1);}else {
                searchPeople.setStatus(0);
            }
            searchPeople.setImgId(Long.valueOf(userMapper.selectfilenamebyid(s.getPetId())));
            userMapper.istschp(searchPeople);
            List<Img_copy1> img_copy1s = userMapper.selectimg(userMapper.selectfilenamebyid(s.getPetId()));
            for (Img_copy1 img_copy1 : img_copy1s) {
                Img i = new Img();
                i.setPath(img_copy1.getPath());
                i.setKeyId(Long.valueOf(img_copy1.getFileName()));
                i.setUsId(userMapper.selectopid(s.getAppleId()));
                userMapper.istimg(i);
            }


        }

            return 0;
    }


    @Override
    public int movespet() {


        List<Search_pet_copy1> search_pet_copy1s = userMapper.selectsearchall();
      //todo 导入宠物
        for (Search_pet_copy1 s : search_pet_copy1s) {
            Pet pet = new Pet();
            pet.setUsId(userMapper.selectopid(s.getAppleId()));
            pet.setName(s.getSearchPetName());
            pet.setAge(s.getSearchPetAge());
            pet.setCreateTime(s.getPublishTime());
            pet.setSubordinate(1);
            pet.setDescribe(s.getSpecialAdvice());
            pet.setSterilization("未知");
            pet.setVaccine("未知");
            pet.setSex(s.getSearchPetSex());
            pet.setType(s.getSearchPetCategory());
            Long varieties;
            Varieties v = new Varieties();
            v.setName(s.getSearchPetVarieties());
            varieties = userMapper.selectvaesid(v);
            pet.setVarieties(String.valueOf(varieties));
            userMapper.istpet(pet);
           //todo 导入寻宠物
            SearchPet searchPet = new SearchPet();
            searchPet.setUsId(userMapper.selectopid(s.getAppleId()));
            Long iii=userMapper.selectid2(pet);
            searchPet.setPetId(userMapper.selectid2(pet));
            searchPet.setWechat(s.getPublisherWechat());
            searchPet.setCreateTime(s.getPublishTime());
            searchPet.setCity(s.getLoseCityArea());
            searchPet.setCounty(s.getLoseCountyArea());
            searchPet.setProvince("");
            searchPet.setAddress(s.getLoseDetailedArea());
            searchPet.setPhone(s.getPublisherPhone());
            searchPet.setExhort(s.getSpecialAdvice());
            if(s.getSearchPetState().equals("ture")){searchPet.setStatus(1);}else {
                searchPet.setStatus(0);
            }
            searchPet.setImgId(Long.valueOf(userMapper.selectfilenamebyid(s.getSearchPetId())));
            userMapper.istschpet(searchPet);
            List<Img_copy1> img_copy1s = userMapper.selectimg(userMapper.selectfilenamebyid(s.getSearchPetId()));
            for (Img_copy1 img_copy1 : img_copy1s) {
                Img i = new Img();
                i.setPath(img_copy1.getPath());
                i.setKeyId(Long.valueOf(img_copy1.getFileName()));
                i.setUsId(userMapper.selectopid(s.getAppleId()));
                userMapper.istimg(i);
            }
        }return 0;}












    /**
     * 返回
     *
     * @param pageNumber 当前页
     * @param pageSize   每页条数
     * @param count      总条数
     * @param list       返回数据
     * @param <T>        泛型
     * @return
     */
    public <T> PageableDetails returnPageable(int pageNumber, Integer pageSize, Integer count, List<T> list) {
        return new PageableDetails<>(pageNumber, pageSize, count, list);
    }


    /**
     * 返回总页数
     *
     * @param total
     * @param pageSize
     * @return
     */
    public int returnPages(int total, int pageSize) {
        return PageUtils.returnPages(total, pageSize);
    }
}









